package com.robotic.sensor.service;

import com.robotic.sensor.domain.SensorData;
import com.robotic.sensor.util.TemperatureDataParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;

/**
 * HSA系列温度传感器Modbus通信服务
 * 支持RS485 Modbus RTU协议
 */
@Service
public class TemperatureSensorService {
    
    private static final Logger log = LoggerFactory.getLogger(TemperatureSensorService.class);
    
    @Autowired
    private ISensorDataService sensorDataService;
    
    @Autowired
    private ModbusRTUService modbusRTUService;
    
    // 寄存器地址定义（根据文档）
    private static final int DEVICE_ID_REGISTER = 0x0080;      // 设备ID
    private static final int EMISSION_RATE_REGISTER = 0x0081;  // 发射率
    private static final int TEMPERATURE_REGISTER = 0x0082;    // 温度
    
    // 功能码定义
    private static final int READ_HOLDING_REGISTERS = 0x03;    // 读取保持寄存器
    private static final int READ_INPUT_REGISTERS = 0x04;      // 读取输入寄存器
    private static final int WRITE_SINGLE_REGISTER = 0x06;     // 写单个寄存器
    private static final int WRITE_MULTIPLE_REGISTERS = 0x10;  // 写多个寄存器
    
    /**
     * 读取温度传感器数据
     * @param deviceId 设备ID (1-247)
     * @param robotId 机器人ID
     * @param taskId 任务ID
     * @param x X坐标
     * @param y Y坐标
     * @return 传感器数据
     */
    public SensorData readTemperatureData(int deviceId, Long robotId, Long taskId, BigDecimal x, BigDecimal y) {
        try {
            log.info("开始读取温度传感器数据，设备ID: {}", deviceId);
            
            // 读取温度寄存器 (功能码0x03)
            byte[] response = modbusRTUService.readHoldingRegisters(deviceId, TEMPERATURE_REGISTER, 1);
            
            if (response != null && response.length >= 2) {
                // 使用数据解析工具解析温度数据
                BigDecimal temperature = TemperatureDataParser.parseTemperature(response);
                
                if (temperature == null) {
                    log.error("温度数据解析失败");
                    return null;
                }
                
                log.info("读取到温度数据: {}", TemperatureDataParser.formatTemperature(temperature));
                
                // 创建传感器数据对象
                SensorData sensorData = new SensorData();
                sensorData.setSensorType("TEMPERATURE");
                sensorData.setValue(temperature);
                sensorData.setDetectTime(new Date());
                sensorData.setCoordinateX(x);
                sensorData.setCoordinateY(y);
                sensorData.setRobotId(robotId.toString());
                sensorData.setTaskId(taskId.toString());
                sensorData.setHandleStatus("0"); // 未处理
                
                return sensorData;
            } else {
                log.error("读取温度数据失败，响应数据无效");
                return null;
            }
            
        } catch (Exception e) {
            log.error("读取温度传感器数据异常: {}", e.getMessage(), e);
            return null;
        }
    }
    
    /**
     * 读取设备信息
     * @param deviceId 设备ID
     * @return 设备信息
     */
    public TemperatureSensorInfo readDeviceInfo(int deviceId) {
        try {
            log.info("读取设备信息，设备ID: {}", deviceId);
            
            TemperatureSensorInfo info = new TemperatureSensorInfo();
            
            // 读取设备ID
            byte[] deviceIdResponse = modbusRTUService.readHoldingRegisters(deviceId, DEVICE_ID_REGISTER, 1);
            if (deviceIdResponse != null && deviceIdResponse.length >= 2) {
                Integer readDeviceId = TemperatureDataParser.parseDeviceId(deviceIdResponse);
                info.setDeviceId(readDeviceId);
            }
            
            // 读取发射率
            byte[] emissionResponse = modbusRTUService.readHoldingRegisters(deviceId, EMISSION_RATE_REGISTER, 1);
            if (emissionResponse != null && emissionResponse.length >= 2) {
                BigDecimal emission = TemperatureDataParser.parseEmissionRate(emissionResponse);
                info.setEmissionRate(emission);
            }
            
            log.info("设备信息读取完成: {}", info);
            return info;
            
        } catch (Exception e) {
            log.error("读取设备信息异常: {}", e.getMessage(), e);
            return null;
        }
    }
    
    /**
     * 设置发射率
     * @param deviceId 设备ID
     * @param emissionRate 发射率 (0.001-1.200)
     * @return 设置是否成功
     */
    public boolean setEmissionRate(int deviceId, BigDecimal emissionRate) {
        try {
            log.info("设置发射率，设备ID: {}, 发射率: {}", deviceId, emissionRate);
            
            // 验证发射率范围
            if (!TemperatureDataParser.isValidEmissionRate(emissionRate)) {
                log.error("发射率超出有效范围(0.001-1.200): {}", emissionRate);
                return false;
            }
            
            // 使用数据解析工具转换发射率
            byte[] rawData = TemperatureDataParser.emissionRateToRawData(emissionRate);
            if (rawData == null) {
                log.error("发射率数据转换失败");
                return false;
            }
            
            // 转换为整数值
            int emissionValue = ((rawData[0] & 0xFF) << 8) | (rawData[1] & 0xFF);
            
            // 写入发射率寄存器
            boolean success = modbusRTUService.writeSingleRegister(deviceId, EMISSION_RATE_REGISTER, emissionValue);
            
            if (success) {
                log.info("发射率设置成功");
            } else {
                log.error("发射率设置失败");
            }
            
            return success;
            
        } catch (Exception e) {
            log.error("设置发射率异常: {}", e.getMessage(), e);
            return false;
        }
    }
    
    /**
     * 批量读取多个传感器数据
     * @param deviceIds 设备ID列表
     * @param robotId 机器人ID
     * @param taskId 任务ID
     * @param x X坐标
     * @param y Y坐标
     * @return 传感器数据列表
     */
    public List<SensorData> readMultipleTemperatureData(List<Integer> deviceIds, Long robotId, Long taskId, BigDecimal x, BigDecimal y) {
        List<SensorData> sensorDataList = new ArrayList<>();
        
        for (Integer deviceId : deviceIds) {
            SensorData data = readTemperatureData(deviceId, robotId, taskId, x, y);
            if (data != null) {
                sensorDataList.add(data);
            }
        }
        
        return sensorDataList;
    }
    
    /**
     * 处理并保存温度传感器数据
     * @param deviceId 设备ID
     * @param robotId 机器人ID
     * @param taskId 任务ID
     * @param x X坐标
     * @param y Y坐标
     * @return 处理结果
     */
    public boolean processAndSaveTemperatureData(int deviceId, Long robotId, Long taskId, BigDecimal x, BigDecimal y) {
        try {
            // 读取温度数据
            SensorData sensorData = readTemperatureData(deviceId, robotId, taskId, x, y);
            
            if (sensorData != null) {
                // 处理实时传感器数据（包含判断和保存）
                return sensorDataService.processRealtimeSensorData(sensorData);
            }
            
            return false;
            
        } catch (Exception e) {
            log.error("处理温度传感器数据异常: {}", e.getMessage(), e);
            return false;
        }
    }
    
    /**
     * 温度传感器设备信息
     */
    public static class TemperatureSensorInfo {
        private Integer deviceId;
        private BigDecimal emissionRate;
        
        // Getters and Setters
        public Integer getDeviceId() {
            return deviceId;
        }
        
        public void setDeviceId(Integer deviceId) {
            this.deviceId = deviceId;
        }
        
        public BigDecimal getEmissionRate() {
            return emissionRate;
        }
        
        public void setEmissionRate(BigDecimal emissionRate) {
            this.emissionRate = emissionRate;
        }
        
        @Override
        public String toString() {
            return "TemperatureSensorInfo{" +
                    "deviceId=" + deviceId +
                    ", emissionRate=" + emissionRate +
                    '}';
        }
    }
}